#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
检查必需文件是否存在
"""

import os
import sys

def check_files():
    """检查必需文件是否存在"""
    print("=== 检查必需文件 ===")
    
    # 获取当前目录
    current_dir = os.path.dirname(os.path.abspath(__file__))
    print(f"当前目录: {current_dir}")
    
    # 必需文件列表
    required_files = [
        'start_full_system.py',
        'simple_web_dashboard.py',
        'run_continuous_spider.py',
        'cnhnb_realtime/spiders/cnhnb_realtime.py',
        'cnhnb_realtime/pipelines.py',
        'cnhnb_realtime/settings.py',
        'requirements_realtime.txt'
    ]
    
    # 可选文件列表
    optional_files = [
        'view_data.py',
        'view_raw_data.py',
        'import_to_hive.py',
        'FRONTEND_INTEGRATION_GUIDE.md'
    ]
    
    print("\n--- 必需文件检查 ---")
    missing_required = []
    for file_path in required_files:
        full_path = os.path.join(current_dir, file_path)
        if os.path.exists(full_path):
            print(f"✓ {file_path}")
        else:
            print(f"✗ {file_path} - 文件不存在")
            missing_required.append(file_path)
    
    print("\n--- 可选文件检查 ---")
    for file_path in optional_files:
        full_path = os.path.join(current_dir, file_path)
        if os.path.exists(full_path):
            print(f"✓ {file_path}")
        else:
            print(f"- {file_path} - 文件不存在（可选）")
    
    print("\n--- 检查结果 ---")
    if missing_required:
        print(f"✗ 缺少 {len(missing_required)} 个必需文件:")
        for file_path in missing_required:
            print(f"  - {file_path}")
        print("\n请确保所有必需文件都已上传到虚拟机")
        return False
    else:
        print("✓ 所有必需文件都存在")
        return True

def check_dependencies():
    """检查Python依赖"""
    print("\n=== 检查Python依赖 ===")
    
    try:
        import scrapy
        print("✓ scrapy")
    except ImportError:
        print("✗ scrapy - 未安装")
    
    try:
        import redis
        print("✓ redis")
    except ImportError:
        print("✗ redis - 未安装")
    
    try:
        import flask
        print("✓ flask")
    except ImportError:
        print("✗ flask - 未安装")
    
    try:
        from kafka import KafkaProducer
        print("✓ kafka-python")
    except ImportError:
        print("✗ kafka-python - 未安装")
    
    try:
        from fake_useragent import UserAgent
        print("✓ fake-useragent")
    except ImportError:
        print("✗ fake-useragent - 未安装")

def check_services():
    """检查服务状态"""
    print("\n=== 检查服务状态 ===")
    
    # 检查Redis
    try:
        import redis
        r = redis.Redis(host='192.168.88.130', port=6379, db=0, decode_responses=True)
        r.ping()
        print("✓ Redis连接正常")
    except Exception as e:
        print(f"✗ Redis连接失败: {e}")
    
    # 检查端口占用
    import subprocess
    try:
        result = subprocess.run(['netstat', '-tlnp'], capture_output=True, text=True)
        if '5000' in result.stdout:
            print("⚠️ 端口5000已被占用")
        else:
            print("✓ 端口5000可用")
    except:
        print("- 无法检查端口占用情况")

def main():
    """主函数"""
    print("惠农网农产品价格监控系统 - 文件检查工具")
    print("=" * 50)
    
    # 检查文件
    files_ok = check_files()
    
    # 检查依赖
    check_dependencies()
    
    # 检查服务
    check_services()
    
    print("\n" + "=" * 50)
    if files_ok:
        print("✓ 文件检查通过，可以启动系统")
        print("启动命令: python3.8 start_full_system.py")
    else:
        print("✗ 文件检查失败，请先解决缺失文件问题")

if __name__ == '__main__':
    main() 